package com.slaoren.mvvmexamp.ui

import com.slaoren.mvvmexamp.R
import com.slaoren.mvvmexamp.databinding.ActivityMvvmDemoBinding
import com.slaoren.mvvmexamp.vm.DemoViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope

/**
 * 横竖屏切换实现示例之一：
 * Activity与Fragment都不切换横竖屏。
 * Fragment在一个布局文件中编写两套布局对应横屏和竖屏时展示，控件状态和文案通过vm来控制，让两套布局中对应控件有相同状态。
 * Fragment实现onConfigurationChanged方法并在其中切换布局。
 */
class MvvmDemo2Activity: BaseActivity<ActivityMvvmDemoBinding, DemoViewModel>(), CoroutineScope by MainScope() {
    override fun getLayoutId(): Int {
        return R.layout.activity_mvvm_demo
    }

    override fun initView() {
        mBinding.vm = mViewModel

        changeFragment("fragment")
    }
    override fun setObserve() {

    }
    override fun loadData() {
    }

    private fun changeFragment(tag: String) {
        val fragmentManager = supportFragmentManager
        val fragmentTransaction = fragmentManager.beginTransaction()
        for (fragmentManagerFragment in fragmentManager.fragments) {
            fragmentTransaction.hide(fragmentManagerFragment)
        }
        var fragment = fragmentManager.findFragmentByTag(tag)
        if (fragment != null) {
            fragmentTransaction.show(fragment)
        } else {
            fragment = when(tag){
                "fragment"->MvvmConfigurationChangedFragment()
                else -> null
            }

            if (fragment != null) {
                fragmentTransaction.add(R.id.frameLayout, fragment, tag)
            }
        }
        fragmentTransaction.commitNow()
    }
}